import 'whatwg-fetch';
import 'custom-event-polyfill';
import 'core-js/stable/promise';
import 'core-js/stable/symbol';
import 'core-js/stable/string/starts-with';
import 'core-js/web/url';
import { history } from 'umi';
import { addGlobalUncaughtErrorHandler } from 'qiankun'; //引入qiankun

import { message } from 'antd';
// import 'less'
import cookie from './utils/cookie';

import themeArr from '../config/themeMap';
import { getCacheData } from './utils/utils';


((global) => {
  global['purehtml'] = {
    bootstrap: () => {
      console.log('purehtml bootstrap');
      return Promise.resolve();
    },
    mount: () => {
      console.log('purehtml mount');
      return render($);
    },
    unmount: () => {
      console.log('purehtml unmount');
      return Promise.resolve();
    },
  };
})(window);

//默认选中一个主题样式
let obj = getCacheData({ key: 'themeApp' })
let obj1 = getCacheData({ key: 'themeHeader' })
document.getElementById('root').className = `${localStorage.themeHeader
    ? JSON.parse(localStorage.themeHeader).name || 'theme1'
    : 'theme1'
  }`;
window.less.modifyVars(obj)
document.getElementById('root').style.filter = (obj1.othersettings && obj1.othersettings.colorWeak) ? 'invert(80%)' : ''
document.querySelectorAll('body')[0].style.filter = (obj1.othersettings && obj1.othersettings.colorWeak) ? 'invert(80%)' : ''

/**
 * 添加全局的未捕获异常处理器
 * 1、捕获子应用加载状态
 */
addGlobalUncaughtErrorHandler((event: Event | string) => {
  console.log(event);
  console.log('=======================================');
  console.log(event.reason.message);
  // history.push('/');
  if (
    (event && event.reason.message === 'Failed to fetch') ||
    (event && event.reason.message === 'Network request failed')
  ) {
    // 子应用加载失败会触发三次，只有第一次要提示，其他略过
    console.log(cookie.getCookie('microAppMount'));
    if (cookie.getCookie('microAppMount') == undefined) {
      cookie.setCookie('microAppMount', 'yes', 3);
      message.error('子应用加载失败，请检查应用是否可正常访问');
      // history.push('/');
    }
  }
  const { message: msg } = event as any;
  // 加载失败时提示
  if (msg && msg.includes('died in status LOADING_SOURCE_CODE')) {
    message.error('子应用加载失败，请检查应用是否可运行');
  }
});

// 请求服务端根据响应动态更新路由
export function patchRoutes(routes) {
  console.log('patchRoutes');
  console.log(routes);
}

// 渲染应用之前做权限校验，不通过则跳转到登录页
export function render(oldRender) {
  console.log('render');
  setTimeout(oldRender, 1000);
}

// 用于在初始加载和路由切换时做一些事情
export function onRouteChange({ location, routes, action }) {
  console.log('onRouteChange');
  console.log(location.pathname);
}
